package cn.rxmind.dlicense.client.starter;

import cn.hutool.core.io.FileUtil;
import cn.rxmind.dlicense.client.starter.annotation.ConditionalOnNotInnerNet;
import cn.rxmind.dlicense.core.base.LicenseBytesReader;
import cn.rxmind.dlicense.core.base.DLicenseContentGetter;
import cn.rxmind.dlicense.core.manager.ScheduleValidateClientLicenseManager;
import cn.rxmind.dlicense.core.manager.DClientLicenseManager;
import cn.rxmind.dlicense.core.utils.SpringEnvironmentUtil;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 自动装配类，主要是为客户端装配客户端证书管理
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2021/4/14 1:53 下午
 */
@Configuration
@ConditionalOnNotInnerNet
public class DLicenseClientAutoConfiguration implements ApplicationContextAware {

    private DClientLicenseManager dClientLicenseManager;

    @Bean
    @ConditionalOnMissingBean(name = "licenseBytesReader", value = LicenseBytesReader.class)
    public LicenseBytesReader licenseBytesReader(){

        return () -> FileUtil.readBytes("/home/utry/license/license.lic");
    }

    /**
     * 向Spring 容器注册证书内容，为了避免将证书管理器暴露给用户，这里注册UtryLicenseContentGetter的一个函数接口实现
     * @return
     */
    @Bean
    public DLicenseContentGetter utryLicenseGetter(){
        return dClientLicenseManager::getDLicenseContent;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Environment environment = applicationContext.getEnvironment();
        SpringEnvironmentUtil.setEnvironment(environment);
        LicenseBytesReader licenseBytesReader = applicationContext.getBean("licenseBytesReader",LicenseBytesReader.class);
        dClientLicenseManager = new ScheduleValidateClientLicenseManager(applicationContext,licenseBytesReader);
        dClientLicenseManager.start();
    }
}
